<template>
  <div>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="clearInput"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchCourse"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="16">
          <el-button
            type="primary"
            @click="showAddDialog"
            style="float: right"
            >添加分类</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="types" style="width: 100%" :header-cell-style="{textAlign: 'center'}" :cell-style="{ textAlign: 'center' }">
        <!-- 表格区 -->
        <el-table-column label="id" prop="id"> </el-table-column>
        <el-table-column label="分类名" prop="type"> </el-table-column>
        <!-- 操作区域 -->
        <el-table-column label="操作" width="130px">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              size="small"
              @click="editType(scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              style="color: #fa6962"
              icon="el-icon-delete"
              size="small"
              @click="removeById(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 15]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <el-input v-model="newType"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getAllType, addType, editType, deleteType } from '#/CourseManagement/course_type.js'
import { addLogs } from '#/Home/Home.js'
export default {
  name: 'CourseCategory',
  meta: {
    title: '课程分类管理'
  },
  data() {
    return {
      queryInfo: {
        query: "",
        pageNum: 1,
        pageSize: 5,
      },
      types: [],
      dialogTitle: '添加分类', // 对话框标题
      dialogVisible: false,
      newType: '',
      editFlag: false,
      // 统计课程分类的总数量
      total: 0,
    };
  },
  created() {
    this.getType()
  },
  methods: {
    // 获取所有课程
    async getType() {
      await getAllType().then(res => {
        const result = res.data
        console.log(result)
        if(result.ret === 0) {
          this.types = result.courseTypes.types
          this.total = this.types.length
        } else {
          this.$message.error('服务器请求错误！');
        }
      })
    },
    showAddDialog() {
      this.dialogTitle = '添加分类'
      this.editFlag = false;
      this.dialogVisible = true;
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    async submit() {
      if(!this.newType) {
        return this.$message.error('请输入类型名称！');
      }
      if(this.editFlag) {
        await editType(this.editFlag, this.newType).then(async res => {
          if(res.status === 200) {
            this.$message.success('修改类型成功！');
            this.dialogVisible = false;
            await addLogs({
              userId: window.sessionStorage.getItem('userId'),
              behavior: '修改了<' + this.newType + '>分类',
            })
            this.getType();
          } else {
            this.$message.error('修改类型出错！');
          }
        })
      } else {
        await addType(this.newType).then(async res => {
          if(res.status === 200) {
            this.$message.success('添加类型成功！');
            this.dialogVisible = false;
            await addLogs({
              userId: window.sessionStorage.getItem('userId'),
              behavior: '添加了<' + this.newType + '>分类',
            })
            this.getType();
          } else {
            this.$message.error('添加类型出错！');
          }
        })
      }
    },
    // 搜索课程
    async searchCourse() {
      if(!this.queryInfo.query) {
        return this.$message.error('请输入名称')
      }
      this.queryInfo.pageNum = 1;
      await searchCourse(this.queryInfo).then(res => {
        if(res.status === 200) {
          this.types = res.data.courses.courses.content
          this.total = res.data.courses.courses.totalElements
          if(this.types === []) {
            this.$message.info('搜索结果为空')
          } else {
            this.$message.success('搜索成功！')
          }
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    // 清除输入框的内容
    clearInput() {
      this.queryInfo.pageNum = 1;
      this.queryInfo.pageSize = 5;
      this.getType();
    },
    // 打开编辑课程对话框
    editType(row) {
      this.editFlag = row.id;
      this.newType = row.type;
      this.dialogTitle = '修改分类';
      this.dialogVisible = true;
    },
    // 删除课程
    async removeById(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if(confirmResult === 'confirm') {
        await deleteType(id).then(res => {
          if(res.status === 200) {
            this.$message.success('成功删除该分类！')
            this.getType()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }
    },
    // 每页的条目数改变
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getType();
    },
    // 页码改变
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage
      this.getType();
    },
  },
};
</script>

<style lang='scss' scoped>
</style>